<template>
  <view>
    <nav-bar :pageTitle="lang.page_name"/>
    <view style="margin:0 30rpx 0 30rpx;" :class="locale">

      <!-- 选择打印方向-->
      <view class="padding-40">
        <radio-group @change="onPaperType" v-model="printType" class="flex-center text-32 gap-30">
          <!-- 两个-->
          <label class="flex-center gap-8 radio-box">
            <view style="margin-inline-end: 10rpx ">{{ lang.print_direction_two }}</view>
            <view style="float: right;">
              <radio checked color="#1073FF" value="0" style="transform:scale(1)"/>
            </view>
          </label>

          <!-- 四个-->
          <label class="flex-center radio-box">
            <view style="margin-inline-end: 10rpx">{{ lang.print_direction_four }}</view>
            <view style="float: right;">
              <radio color="#1073FF" value="1" style="transform:scale(1)"/>
            </view>
          </label>
        </radio-group>
      </view>

      <!-- 两个户口-->
      <view v-if="printType === 0" class="column gap-20 ltr a4">
        <!-- 户口选自框大 box-->
        <view v-for="(item, index) in twoRegistration" :key="index" class="column-center gap-20">
          <view class="registration-card-box">
            <view v-if="item.file === ''" hover-class="hover" @click="showUploadImage(index)">
              <view class="column-center icon-card-box">
                <view class="flex-column icon-card">
                  <u-icon size="44px" color="#1073FF" name="camera"/>
                </view>
              </view>
              <image class="registration" :src="`/static/print_id/${item.icon}.png`"/>
            </view>

            <template v-else>
              <view class="close-icon-box" @click="closeRegistration(index)">
                <u-icon size="26px" color="#0009" name="close-circle-fill"/>
              </view>
              <view @click="onEditImage(index)">
                <image class="registration" :src="item.file"/>
              </view>
            </template>
          </view>
          <view class="text-32">{{ lang[item.name] }}</view>
        </view>
      </view>

      <!-- 四个户口-->
      <view v-if="printType === 1" class="card flex-row wrap gap-20 ltr a4-horizontal">
        <!-- 户口选自框大 box-->
        <view v-for="(item, index) in fourRegistration" :key="index" class="column-center gap-20">
          <view class="horizontal-registration-card-box">
            <view v-if="item.file === ''" hover-class="hover" @click="showUploadImage(index)">
              <view class="column-center icon-card-box">
                <view class="flex-column icon-card">
                  <u-icon size="34px" color="#1073FF" name="camera"/>
                </view>
              </view>
              <image class="horizontal-registration" :src="`/static/print_id/${item.icon}.png`"/>
            </view>

            <template v-else>
              <view class="horizontal-close-icon-box" @click="closeRegistration(index)">
                <u-icon size="26px" color="#0009" name="close-circle-fill"/>
              </view>
              <view @click="onEditImage(index)">
                <image class="horizontal-registration" :src="item.file"/>
              </view>
            </template>
          </view>
          <view class="text-28">{{ lang[item.name] }}</view>
        </view>
      </view>


      <!-- 打印-->
      <view style="margin-top: 30rpx; padding: 20rpx">
        <u-button
            shape="circle" :customStyle="{fontSize: '32rpx' }"
            @click="registrationDrawAndShareImage" size="large" color="#1073FF">
          {{ otherLang.print }}
        </u-button>
      </view>

      <!-- a4 打印-->
      <view class="canvas">
        <canvas style="width: 1588px; height: 2246px; " canvas-id="registrationCanvas" id="registrationCanvas"/>
      </view>

      <!--    上传中弹窗-->
      <!--      <my_upload_card :upload-name="lang.registration_upload" :show="showUpload" :upload-progress="uploadProgress"/>-->

      <!-- 选择弹窗-->
      <upload-select-popup
          :show-popup="showUploadPopup" @choose-message="chooseMessage" @choose-image="chooseImage"
          @close-popup="showUploadPopup = false"/>
    </view>
  </view>
</template>

<script>
import navBar from "@/components/nav-bar/nav-bar.vue";
import my_upload_card from "@/components/my_upload_card/index.vue";
import uploadSelectPopup from "@/components/upload-select-popup/upload-select-popup.vue";
import {editImageChange} from "@/utils/utils";
import {uploadImageServer} from "@/services/office";

export default {
  name: "print_registration",
  components: {navBar, uploadSelectPopup, my_upload_card},
  data() {
    return {
      printType: 0,
      twoRegistration: [
        {name: 'registration_front', file: '', icon: 'registration'},
        {name: 'registration_after', file: '', icon: 'registration_sel'}
      ],

      fourRegistration: [
        {name: 'registration_front', file: '', icon: 'registration'},
        {name: 'registration_after', file: '', icon: 'registration_sel'},
        {name: 'registration_after', file: '', icon: 'registration_sel'},
        {name: 'registration_after', file: '', icon: 'registration_sel'}
      ],

      showUploadPopup: false,
      showUpload: false,
      uploadProgress: 0,
    };
  },
  computed: {
    lang() {
      return this.$t('print_registration')
    }
  },
  methods: {
    // 选择打印方向
    onPaperType(event) {
      this.printType = parseInt(event.detail.value)
      console.log(this.printType)
    },
    // 上传文件弹窗
    showUploadImage(type) {
      this.clickType = type;
      this.showUploadPopup = true;
    },
    // 微信选取图片
    chooseMessage() {
      const that = this;
      uni.chooseMessageFile({
        count: 1,
        type: 'image',
        success(res) {
          console.log(res)
          that.processImage(res.tempFiles[0].path)
        }
      });
    },

    // 本地图片上传或拍照
    chooseImage(index) {
      const that = this;
      const sourceTypes = ['camera', 'album'];
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: [sourceTypes[index]],
        sizeType: ['original', 'compressed'],
        success: function (res) {
          that.processImage(res.tempFiles[0].tempFilePath);
        }
      });
    },

    // 处理图片编译
    async processImage(src) {
      try {
        if (this.printType === 0) {
          this.twoRegistration[this.clickType].file = await editImageChange(src);
        } else {
          this.fourRegistration[this.clickType].file = await editImageChange(src);
        }
      } catch (error) {
        console.error('图片处理失败:', error);
      }
    },

    // 删除照片
    closeRegistration(type) {
      if (this.printType === 0) {
        this.twoRegistration[type].file = '';
      } else {
        this.fourRegistration[type].file = '';
      }
    },

    // 编译照片
    onEditImage(type) {
      this.clickType = type;
      let url = '';
      if (this.printType === 0) {
        url = this.twoRegistration[type].file;
      } else {
        url = this.fourRegistration[type].file;
      }
      this.processImage(url)
    },

    // 合成图片
    registrationDrawAndShareImage() {
      const registrationWidth = 1120;      // 户口宽度
      const registrationHeight = 828;     // 户口高度
      const a4Width = 1588;                // A4纸宽度
      const a4Height = 2246;               // A4纸高度

      // 检查是否已上传照片
      if (this.printType === 0) {
        if (!this.twoRegistration[0].file && !this.twoRegistration[1].file) {
          uni.showToast({title: "请先上传图片", icon: 'none'});
          return;
        }
      } else {
        if (!this.fourRegistration[0].file && !this.fourRegistration[1].file &&
            !this.fourRegistration[2].file && !this.fourRegistration[3].file) {
          uni.showToast({title: "请先上传图片", icon: 'none'});
          return;
        }
      }

      uni.showLoading({title: '加载中....', mask: true});

      const context = uni.createCanvasContext('registrationCanvas', this);
      context.fillStyle = "#FFFFFF";  // 背景颜色
      context.fillRect(0, 0, a4Width, a4Height); // 填充背景

      // 设置间距值
      const verticalSpacing = 40; // 增加的上下间距（可以修改此值以调整上下图像的距离）
      const horizontalSpacing = 40; // 增加的左右间距（可以修改此值以调整左右图像的距离）

      if (this.printType === 0) {
        // 第一种情况：绘制两张户口照片
        const firstImageY = (a4Height / 2 - registrationHeight - verticalSpacing / 2); // 第一张图片的Y坐标
        const secondImageY = (a4Height / 2 + verticalSpacing / 2); // 第二张图片的Y坐标

        context.drawImage(this.twoRegistration[0].file, (a4Width - registrationWidth) / 2, firstImageY - 180, registrationWidth, registrationHeight);
        context.drawImage(this.twoRegistration[1].file, (a4Width - registrationWidth) / 2, secondImageY - 180, registrationWidth, registrationHeight);
      } else {
        // 第二种情况：绘制四张户口照片
        const offsetX = (a4Width - 2 * registrationHeight - horizontalSpacing) / 2; // 水平方向的偏移
        const offsetY = (a4Height - 2 * registrationWidth - verticalSpacing) / 2 + 24; // 垂直方向的偏移

        // 绘制第一张图像 (左边上面的)
        context.save();
        context.translate(offsetX + registrationHeight / 2, offsetY + registrationWidth / 2);
        context.rotate(Math.PI / 2);
        context.drawImage(this.fourRegistration[0].file, -registrationWidth / 2, -registrationHeight / 2, registrationWidth, registrationHeight);
        context.restore();

        // 绘制第二张图像 (左边下面的)
        context.save();
        context.translate(offsetX + registrationHeight / 2, offsetY + registrationWidth / 2 + registrationHeight + verticalSpacing + 240);
        context.rotate(Math.PI / 2);
        context.drawImage(this.fourRegistration[1].file, -registrationWidth / 2, -registrationHeight / 2, registrationWidth, registrationHeight);
        context.restore();

        // 绘制第三张图像 (右边上面的)
        context.save();
        context.translate(offsetX + registrationHeight + horizontalSpacing + registrationHeight / 2, offsetY + registrationWidth / 2);
        context.rotate(Math.PI / 2);
        context.drawImage(this.fourRegistration[2].file, -registrationWidth / 2, -registrationHeight / 2, registrationWidth, registrationHeight);
        context.restore();

        // 绘制第四张图像 (右边下面的)
        context.save();
        context.translate(offsetX + registrationHeight + horizontalSpacing + registrationHeight / 2, offsetY + registrationWidth / 2 + registrationHeight + verticalSpacing + 240);
        context.rotate(Math.PI / 2);
        context.drawImage(this.fourRegistration[3].file, -registrationWidth / 2, -registrationHeight / 2, registrationWidth, registrationHeight);
        context.restore();
      }

      context.draw();

      // 生成图像并保存到相册
      setTimeout(() => {
        uni.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: a4Width,
          height: a4Height,
          destWidth: a4Width,
          destHeight: a4Height,
          canvasId: 'registrationCanvas',
          success(res) {
            console.log("registrationCanvas -=-=", res);
            // 上传图片到服务器
            uni.uploadFile({
              url: uploadImageServer,
              name: 'file',
              filePath: res.tempFilePath,
              success: (res) => {
                console.log("success: (res) => -=-=-", res)
                const {code, data: {url}} = JSON.parse(res.data);
                console.log("Upload success:", JSON.parse(res.data).data);
                if (code === 200) {
                  uni.navigateTo({url: `/pages/photo_pay/photo_pay?type=1&image=` + encodeURIComponent(JSON.stringify(url))})
                }
              },
              fail: (err) => {
                console.error('Upload failed:', err);
              }, complete: () => {
                uni.hideLoading()
              }
            });
          }
        });
      }, 2000);
    },
  },
}
</script>

<style lang="scss">
.a4-vertical {
  height: 1100rpx;
}

.registration-card-box {
  width: 514rpx;
  height: 394rpx;
  position: relative;
  border-radius: 16rpx;
  padding: 4rpx;
  border: 2rpx dashed #1073FF;
}

.registration {
  width: 500rpx;
  height: 380rpx;
  border-radius: 16rpx;
}

.a4-horizontal {
  height: 600rpx;
}

.horizontal-registration-card-box {
  width: 304rpx;
  height: 210rpx;
  position: relative;
  border-radius: 16rpx;
  padding: 4rpx;
  border: 2rpx dashed #1073FF;
}

.horizontal-registration {
  width: 294rpx;
  height: 200rpx;
  border-radius: 16rpx;
}

.horizontal-close-icon-box {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
}

</style>
